<?php
/**
 * Created by PhpStorm.
 * User: Thai Dac Vinh
 * Date: 4/15/14
 * Time: 4:12 PM
 */
require_once 'config.php';
require_once 'DatastoreService.php';
require_once 'Google/Client.php';
require_once 'Google/Auth/AssertionCredentials.php';
require_once 'Google/Service/Datastore.php';

function get_en_card_info() {
    return get_card_info(EN_CARD_KIND);
}

function get_cn_card_info() {
    return get_card_info(CN_CARD_KIND);
}

function get_card_info($card_kind) {
    global $google_api_config;
    DatastoreService::setInstance(new DatastoreService($google_api_config));

    try {
        // test the config and connectivity by creating a test entity, building
        // a commit request for that entity, and creating/updating it in the datastore
        $sql = 'SELECT * FROM ' . $card_kind;
        $req = create_card_query_request($sql);
        /**
         * @var Google_Service_Datastore_RunQueryResponse $result
         */
        $result = DatastoreService::getInstance()->runQuery($req);
        $result = $result->toSimpleObject();
        $entity_results = $result->batch['entityResults'];
        $dataset = array();
        foreach ($entity_results as $entity) {
            $name = $entity['entity']['key']['path'][0]['name'];
            $count = $entity['entity']['properties']['count']['stringValue'];
            $dataset[$name] = intval($count);
        }
        return $dataset;
    } catch (Google_Exception $ex) {
//        syslog(LOG_WARNING, 'Commit to Cloud Datastore exception: ' . $ex->getMessage());
        echo $ex->getMessage();
        echo "There was an issue -- check the logs.";
        return false;
    }
}

function create_card_query_request($sql) {
//    $entity = create_entity();

//    $mutation = new Google_Service_Datastore_Mutation();
//    $mutation->setUpsert([$entity]);
    $req = new Google_Service_Datastore_RunQueryRequest();
    $query = new Google_Service_Datastore_GqlQuery();
    $query->setQueryString($sql);
    $req->setGqlQuery($query);
    return $req;
}

function set_en_card_learned_count($row_key, $value) {
    set_card_learned_count(EN_CARD_KIND, $row_key, $value);
}

function set_en_card_tested_count($row_key, $value) {
    set_card_learned_count(EN_CARD_KIND, $row_key, $value);
}

function set_cn_card_learned_count($row_key, $value) {
    set_card_learned_count(CN_CARD_KIND, $row_key, $value);
}

function set_card_learned_count($card_kind, $row_key, $value) {
    $kind = $card_kind;
    $field_name = 'count';
    set_card_info($kind, $row_key, $field_name, $value);
}

function set_card_info($kind, $row_key, $field_name, $value) {
    global $google_api_config;
    $scopes = [
        "https://www.googleapis.com/auth/datastore",
        "https://www.googleapis.com/auth/userinfo.email",
    ];

    $client = new Google_Client();
    $client->setApplicationName($google_api_config['application-id']);
    $client->setAssertionCredentials(new Google_Auth_AssertionCredentials(
        $google_api_config['service-account-name'],
        $scopes, $google_api_config['private-key']));

    $service = new Google_Service_Datastore($client);
    $service_dataset = $service->datasets;
    $dataset_id = $google_api_config['dataset-id'];

    try {
        // test the config and connectivity by creating a test entity, building
        // a commit request for that entity, and creating/updating it in the datastore
        $req = create_card_update_request($kind, $row_key, $field_name, $value);
        $service_dataset->commit($dataset_id, $req, []);
    } catch (Google_Exception $ex) {
//    syslog(LOG_WARNING, 'Commit to Cloud Datastore exception: ' . $ex->getMessage());
        echo $ex->getMessage();
        echo "There was an issue -- check the logs.";
        return;
    }
}

function create_card_update_request($kind, $row_key, $field_name, $value) {
    $entity = create_entity($kind, $row_key, $field_name, $value);

    $mutation = new Google_Service_Datastore_Mutation();
    $mutation->setUpsert([$entity]);

    $req = new Google_Service_Datastore_CommitRequest();
    $req->setMode('NON_TRANSACTIONAL');
    $req->setMutation($mutation);
    return $req;
}

function create_entity($kind, $row_key, $field_name, $value) {
    $entity = new Google_Service_Datastore_Entity();
    $key = create_key($kind, $row_key);
    $entity->setKey($key);
    $string_prop = new Google_Service_Datastore_Property();
    $string_prop->setStringValue($value);
    $property_map = [];
    $property_map[$field_name] = $string_prop;
    $entity->setProperties($property_map);
    return $entity;
}

function create_key($kind, $row_key) {
    $path = new Google_Service_Datastore_KeyPathElement();
    $path->setKind($kind);
    $path->setName($row_key);
    $key = new Google_Service_Datastore_Key();
    $key->setPath([$path]);
    return $key;
}